<template>
  <div class="addsite">
    <div class="title">
      <h1>地点信息</h1>
      <van-button 
        class="tbtn" style="text-align:right" round type="warning" icon="location-o" size="small"
        @click="locator"
      >定 位</van-button>
    </div>
    <van-cell-group inset class="cell">
      <!-- 名称 -->
      <van-field
        v-model="site.name"
        label-width="5em"
        label="名称"
        placeholder="这里是地址名称"
      />
      <!-- 坐标 -->
      <van-field
        v-model="site.site"
        label-width="5em"
        label="坐标"
        placeholder="这里是坐标"
      />
      <!-- 地址 -->
      <van-field
        v-model="areaSelect"
        label-width="5em"
        is-link
        readonly
        label="地区"
        placeholder="点击选择省市区"
        @click="showArea = true"
      />
      <van-popup v-model:show="showArea" position="bottom">
        <van-area
          :area-list="areaList"
          @confirm="onConfirm"
          @cancel="showArea = false"
        />
      </van-popup>
      <!-- 街道 -->
      <van-field
        v-model="site.street"
        label-width="5em"
        label="街道"
        placeholder="这里是街道"
        autosize
      />
      <!-- 按钮 -->
      <van-row justify="center">
        <van-col span="8">
          <van-button plain class="btn" round type="primary" @click="handleClaer">清 空</van-button>
        </van-col>
        <van-col span="8" offset="2">
          <van-button class="btn" round type="primary" @click="handleSubmit">提 交</van-button>
        </van-col>
      </van-row>
    </van-cell-group>
    <van-notice-bar
      style="margin:10px"
      wrapable
      :scrollable="false"
      text="点击定位可以使用浏览器的定位功能，自动获取当前位置的部分信息，若无法精确定位，根据IP返回城市地标；自定义位置时，可以进行坐标拾取，建议经纬度与所选择位置信息一致。"
    />
    <div class="btn-point">
      <van-button type="primary" plain size="mini" @click="getPoint('bd')">百度坐标拾取</van-button>
      <van-button type="primary" plain size="mini" @click="getPoint('tx')">腾讯坐标拾取</van-button>
    </div>
  </div>
</template>
<script>
import { areaList } from '@vant/area-data';
export default {
  data(){
    return {
      site: {
        name: "",
        site: "",
        province: "",
        city: "",
        district: "",
        street:"",
        creater:""
      },
      areaList, // 引入的地址信息
      showArea: false,
      areaSelect:"" // 拼接的地址信息
    }
  },
  created(){
    // 如果没登录进行登录
    if(!this.$store.state.uid){
      this.$router.push('login')
    }
    // 如果有缓存加载缓存内容
    let cache = this.$store.getters.getCache("site")
    if(cache){
      this.site = {...cache}
      this.areaSelect = (cache.province?cache.province:"请选择")+"/"+
        (cache.city?cache.city:"请选择")+"/"+
        (cache.district?cache.district:"请选择")
    }else{
      cache = this.$store.getters.getCache("user")
      // 如果sid已经存在则查询
      if(cache && cache.sid!=""){
        this.axios.get("getsite",{
          params:{
            sid: cache.sid
          }
        }).then(res=>{
          if(res.data){
            // 如果查到数据
            console.log(res.data);
            this.site = {...res.data}
            this.areaSelect = (res.data.province?res.data.province:"请选择")+"/"+
              (res.data.city?res.data.city:"请选择")+"/"+
              (res.data.district?res.data.district:"请选择")
          }
        })
      }
    }

  },
  // 缓存编辑的信息
  beforeUnmount(){
    // 防止刷新进去时缓存
    if(this.$store.state.uid){
      this.$store.commit("setCache",{site:this.site})
    }
  },
  methods:{
    // 定位
    locator(){
      let scope = this
      let geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
          scope.site = {
            name: scope.$store.state.uid+"创建的地点",
            site: "["+r.point.lng+","+r.point.lat+"]",
            province: r.address.province,
            city: r.address.city,
            district: r.address.district,
            street: r.address.street
          }
          scope.areaSelect = (r.address.province?r.address.province:"请选择")+"/"+
            (r.address.city?r.address.city:"请选择")+"/"+
            (r.address.district?r.address.district:"请选择")
        }
        else {
          console.log('failed'+this.getStatus());
        }  
      })
    },
    // 选择地区
    onConfirm(area){
      this.showArea = false
      this.areaSelect = area.filter((item) => !!item)
        .map((item) => item.name)
        .join('/');
      this.site.province = area[0].name
      this.site.city = area[1].name
      this.site.district = area[2].name
    },
    // 坐标拾取
    getPoint(name){
      let href = "https://api.map.baidu.com/lbsapi/getpoint/"
      if(name=="bd"){
        href = "https://api.map.baidu.com/lbsapi/getpoint/"
      }else if(name=="tx"){
        href = "https://lbs.qq.com/getPoint/"
      }
      window.open(href, '_blank');
    },
    // 提交信息
    handleSubmit(){
      if(this.site.district==""){
        // 请选择完整的区域
        this.$notify({ type: 'warning', message: '请选择完整的区域!' })
        return
      }
      if(this.site.street==""){
        // 请填写街道的信息
        this.$notify({ type: 'warning', message: '请填写街道的信息!' })
        return
      }
      // 记录是谁创建的
      this.site.creater = this.$store.state.uid
      this.axios.get('addsite',{
        params:this.site
      }).then(res=>{
        // 如果失败返回null
        if(res.data){
          // 如果成功返回地点id
          this.$store.commit("setCacheSidAndName",{sid:res.data.sid,sname:this.site.name})
          history.back()
        }
      })
    },
    // 清除记录
    handleClaer(){
      for(let i in this.site){
        this.site[i] = ""
      }
      this.site.name = this.$store.state.uid+"创建的地点"
      this.areaSelect = "请选择/请选择/请选择"
    }
  }
}
</script>
<style lang="scss" scoped>
.btn-point{
  margin: 4px 16px;
  text-align: right;
}
.btn{
  margin-top: 20px;
  width: 100%;
  flex: 1;
}
.cell{
  text-align: left;
  padding: 16px 0;
}
.title{
  position: relative;
  .tbtn{
    position: absolute;
    right: 30px;
    top: 14px;
  }
}
</style>